package com.weshare.nd.netty.coder;

import com.alibaba.fastjson.JSON;
import com.weshare.nd.model.ChatMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ChatDecode extends ByteToMessageDecoder {


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }

        byteBuf.markReaderIndex();  //标记一下当前的readIndex的位置
        int dataLength = byteBuf.readInt();
        if (dataLength < 0) {
            channelHandlerContext.close();
            return;
        }

        if (byteBuf.readableBytes() < dataLength) { //如果读到的消息体长度小于传送过来的消息长度，则resetReaderIndex,重置读取位置
            byteBuf.resetReaderIndex();
            return;
        }

        byte[] msgBytes = new byte[dataLength];
        byteBuf.readBytes(msgBytes);

        String jsonMsg = new String(msgBytes);

        ChatMessage chatMsg = JSON.parseObject(jsonMsg, ChatMessage.class);

        list.add(chatMsg);
    }
}
